package com.poe.controller.book;
import com.poe.entity.Book;
import com.poe.service.ibook.BookService;
import com.poe.vo.PageParam;
import net.sf.json.JSONObject;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@Controller
@RequestMapping("book")
public class BookController {
	private static Logger log = LogManager.getLogger(BookController.class);
	@Autowired
    BookService bookService;
	//总页数
	int allPage;
	//当前页
	int	currentNum;
	//点击的上一页下一页
	String tag;
	//开始页数
	int startPage;
	
//分页查询
	@RequestMapping("findBook")
	public void findBook(HttpServletResponse response, PageParam pageParam) throws IOException {
		response.setCharacterEncoding("UTF-8");
		PrintWriter pw=response.getWriter();
		//查询所有的书
		List<Book> allBookList=bookService.findAllBook();
		//用来装返回分页的数据
		PageParam pageParam1=new PageParam();
		
		allPage=allBookList.size()%12==0?allBookList.size()/12:allBookList.size()/12+1;
		tag=pageParam.getTag();
		currentNum=pageParam.getCurrentNum();
		if(null!=tag){
			switch (tag) {
			case "up":
				if(currentNum==1){
					 currentNum=1;
				 }else{
					 currentNum--;
				 }
				break;
			case "next":
				if(currentNum==allPage){
					 currentNum=allPage;
				 }else{
					 currentNum++;
				 }
				break;
			default:
				break;
			}
		}
		startPage=(currentNum-1)*12;
		List<Book> listPage=bookService.findBook(startPage);
		pageParam1.setCurrentNum(currentNum);
		pageParam1.setListPage(listPage);
		pageParam1.setAllPage(allPage);
		String a=JSONObject.fromObject(pageParam1).toString();
    	pw.write(a);
    	pw.flush();
    	pw.close();
	}

//查询书的详情
	@RequestMapping("findBookProduct")
	public String findBookProduct(HttpServletRequest request, String bookId) throws IOException {
		Book book=bookService.findBookProduct(bookId);
		if(null!=book){
			request.setAttribute("bookProduct", book);
			return "product";
		}
		return "error";
	}
}
